package com.sinodata.bsm.cicp.collector.windows;

import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CollectorUtil;
import com.sinodata.bsm.cicp.util.FileAttribute;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class FileMakeCollector extends Collector {
    private static Logger logger = Logger.getLogger(com.sinodata.bsm.cicp.collector.windows.FileMakeCollector.class);
    private static String fileName = "";
    private static int TIMEOUT = 300;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> result = new ArrayList<ResPropertyValue>();
        ResPropertyValue value = new ResPropertyValue();
        String[] propMetas = this.getPropMeta();
        ResPropertyValue.PropValue[] propValue = new ResPropertyValue.PropValue[propMetas.length];
        String path = this.getParamMap().get("FileDirectory").trim();
        String date = getRemoteCurrentTime(ip);
        Pattern pattern = Pattern.compile("\\s*(\\d{4})-(\\d{2})-(\\d{2})");
        Matcher matcher = pattern.matcher(date);
        Calendar time = Calendar.getInstance();
        if (matcher.find()) {
            time.set(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)) - 1, Integer.parseInt(matcher.group(3)));
            time.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            fileName = sdf.format(time.getTime()) + ".mdc";
        }

        FileAttribute currentAttribute = CollectorUtil.getNewestRemoteFileByPatternWin(path, fileName, ip);
        if (currentAttribute == null || "".equals(fileName)) {
            propValue[0] = ResPropertyValue.createPropValue("NO", propMetas[0]);
            propValue[1] = ResPropertyValue.createPropValue("", propMetas[1]);
            propValue[2] = ResPropertyValue.createPropValue(date, propMetas[2]);
            propValue[3] = ResPropertyValue.createPropValue("0", propMetas[3]);
            value.setValues(propValue);
            result.add(value);
            return result;
        }

        String[] arr = new String[4];
        //文件名
        arr[0] = getFileName(currentAttribute.name, path);
        //文件最后修改时间
        String fileTime = currentAttribute.lastModification;
        arr[1] = "" + getDateMillisForCMD(fileTime.trim());
        //远端机器时间,采集时间
        arr[2] = "" + date;
        //文件大小
        arr[3] = currentAttribute.size + "";

        propValue[0] = ResPropertyValue.createPropValue(arr[0], propMetas[0]);
        propValue[1] = ResPropertyValue.createPropValue(arr[1], propMetas[1]);
        propValue[2] = ResPropertyValue.createPropValue(arr[2], propMetas[2]);
        propValue[3] = ResPropertyValue.createPropValue(arr[3], propMetas[3]);
        value.setValues(propValue);
        result.add(value);
        return result;

    }

    private String getFileName(String fullName, String path) {
        fullName = fullName.trim();
        path = path.trim();
        if (path.endsWith("\\"))
            fullName = fullName.substring(path.length());
        else
            fullName = fullName.substring(path.length() + 1);
        return fullName;
    }

    private long getDateMillisForCMD(String date) {
        Calendar calendar = Calendar.getInstance();
        int i = Integer.parseInt(date.substring(0, 4));
        calendar.set(Calendar.YEAR, i);
        i = Integer.parseInt(date.substring(4, 6));
        calendar.set(Calendar.MONTH, i - 1);
        i = Integer.parseInt(date.substring(6, 8));
        calendar.set(Calendar.DAY_OF_MONTH, i);
        i = Integer.parseInt(date.substring(8, 10));
        //在Windows的GetNewesRemoteFileInfo.exe取出的时间是格林威治时间0:00的时间
        //北京时间是东八区,所以需要加8小时.
        //本来应该在此可执行程序中加,不过小弟的c语言十分汗颜不会加就加在这里了
        //Modify by Credible_zhang at 200604021242
        calendar.set(Calendar.HOUR_OF_DAY, i + 8);
        i = Integer.parseInt(date.substring(10, 12));
        calendar.set(Calendar.MINUTE, i);
        i = Integer.parseInt(date.substring(12));
        calendar.set(Calendar.SECOND, i); //设置完年／月／日／小时／分钟／秒
        return calendar.getTimeInMillis(); //转换为毫秒
    }

    /**
     * 获得远程主机的当前采集时间
     *
     * @param ip
     * @return
     * @throws CollectorException
     */
    private String getRemoteCurrentTime(String ip) throws CollectorException {
        BufferedReader reader = null;
        String date = "";
        String time = "";
        try {
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("date /T", ip, TIMEOUT);
            String readLine = reader.readLine();
            if (readLine != null) {
                date = readLine;
            }
            reader = com.sinodata.bsm.cicp.util.CollectorUtil.getReader("time /T", ip, TIMEOUT);
            readLine = reader.readLine();
            if (readLine != null) {
                time = readLine;
            }
        } catch (Exception e) {
            logger.error("failed to call " + this.getClass().getName() + ".getRemoteCurrentTime()", e);
            throw new CollectorException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                logger.error("failed to close BufferReader", e);
            }

        }
        return date + " " + time;
    }

    @Override
    public String[] getParamMeta() {
        //return new String[] { "文件路径" }
        return new String[] { "FileDirectory" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "文件名", "处理时间", "采集时间", "文件大小" };
        return new String[] { "FileName", "HandleTime", "CollectTime", "FileSize" };
    }

}
